﻿#!/usr/bin/env python
#coding=utf-8
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.db import GqlQuery
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.api import urlfetch
import md5
import hmac
import base64
from time import gmtime, strftime, time
import urllib

class TaobaoA(webapp.RequestHandler):
  def get(self):
    top_appkey = self.request.get("top_appkey")
    top_parameters = self.request.get("top_parameters")
    top_session = self.request.get("top_session")
    top_sign = self.request.get("top_sign")
    top_secret = "f0c6c58234a0e707d4d4ff60e8ae2c63"
    m = md5.new()
    m.update(top_appkey)
    m.update(top_parameters)
    m.update(top_session)
    m.update(top_secret)
    base64str = base64.b64encode(m.digest())

    state = -1
    if cmp(base64str, top_sign)==0:
        result_str = u"签名通过 \n".encode("utf-8")
        base64strdec = base64.b64decode(top_parameters)
        strparse = base64strdec.split('&')
        ts = strparse[1].split('=')
        time_session = int(ts[1])/1000
        time_now = time()
        #state = 1
        #self.response.out.write((time_now - time_session)/60)
        if  time_session > ( time_now + 60 * 10 ) or time_now > ( time_session + 60 * 30 ):
            result_str += u"超时退出 ".encode("utf-8")
        else:
            nick = strparse[5].split('=')
            result_str += u"有效时间内 ".encode("utf-8")
            result_str += u"你好 ".encode("utf-8")+nick[1]
            state = 0
    else:
      result_str = u"签名失败 \n".encode("utf-8")
      #return

    template_values = {
        'result_string':    result_str,
        'state':            state,
    }
    path = os.path.join(os.path.dirname(__file__), 'view_taobaoA.html')
    self.response.out.write(template.render(path, template_values))
    
  def post(self):
    name = self.request.get("name")
    page_no = self.request.get("page_no")
    r = search_taobao(name, page_no)
    self.response.out.write(r.content.decode("UTF-8"))
    return

def search_taobao(name, page_no):
    t = strftime("%Y-%m-%d %H:%M:%S", gmtime(time()+8*60*60))
    sign = sign_caculate(page_no, name, t)
    url = """http://gw.api.taobao.com/router/rest?\
app_key=12123092&\
fields=name,price&\
format=json&\
method=taobao.products.search&\
page_no=%s&\
page_size=100&\
q=%s&\
sign_method=md5&\
timestamp=%s&\
v=2.0&\
sign=%s""" % (page_no, urllib.quote(name.encode("UTF-8")), t, sign)
    url = url.replace(' ','%20')
    #self.response.out.write(url)
    result = urlfetch.fetch(url=url)
    return result

def sign_caculate(page_no, name, time):
    #m = hmac.new("")
    m = md5.new()
    m.update("f0c6c58234a0e707d4d4ff60e8ae2c63")
    m.update("app_key")
    m.update("12123092")
    m.update("fields")
    m.update("name,price")
    m.update("format")
    m.update("json")
    m.update("method")
    m.update("taobao.products.search")
    m.update("page_no")
    m.update(page_no)
    m.update("page_size")
    m.update("100")
    m.update("q")
    m.update(name.encode("UTF-8"))
    m.update("sign_method")
    m.update("md5")
    #m.update("hmac")
    m.update("timestamp")
    m.update(time)
    m.update("v")
    m.update("2.0")
    m.update("f0c6c58234a0e707d4d4ff60e8ae2c63")
    return m.hexdigest().upper()
